package com.crr.service.impl;

import com.crr.apis.AccountFeignApi;
import com.crr.apis.StorageFeignApi;
import com.crr.entities.Order;
import com.crr.mapper.OrderMapper;
import com.crr.ret.ResultData;
import com.crr.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private StorageFeignApi storageFeignApi;
    @Resource
    private AccountFeignApi accountFeignApi;

    @Override
    @GlobalTransactional(name = "crr-create-order",rollbackFor = Exception.class)
    public void create(Order order) {
        //xid全局事务Id的检查
        String xid = RootContext.getXID();
        //新建订单
        log.info("----------开始新建订单" + "\t" + "xid：" + xid);
        //订单新建时 默认初始订单状态 0
        order.setStatus(0);
        int insert = orderMapper.insert(order);
        //插入订单成功后获取插入mysql的实体对象
        Order orderFormDB = null;
        if (insert > 0) {
            //从mysql中查出刚插入的数据
            orderFormDB = orderMapper.selectOne(order);
            log.info("--------------结束新建订单成功" + "\t" + "orderFormDB：" + orderFormDB);
            System.out.println();
            log.info("--------------扣减库存");
            //扣减库存
            storageFeignApi.decrease(order.getProductId(), order.getCount());
            log.info("--------------扣减库存成功");
            //扣减余额
            log.info("--------------扣减余额");
            accountFeignApi.decrease(order.getUserId(), order.getMoney());
            log.info("--------------扣减余额成功");
            //修改订单状态
            log.info("--------------修改订单状态");

            
            Example example = new Example(Order.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", orderFormDB.getUserId());
            criteria.andEqualTo("status", 0);
            orderFormDB.setStatus(1);
            orderMapper.updateByExampleSelective(orderFormDB, example);
            log.info("-------------> 修改订单状态成功");


        }
        System.out.println();
        log.info("---------------------结束新建订单" + "\t" + "xid：" + xid);

    }
}
